package com.xiaozhen.sso.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaozhen.sso.dao.AuthUserDao;
import com.xiaozhen.sso.domain.MyAuthUser;
import com.xiaozhen.sso.service.LoginService;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ： 甄维胜
 * @createTime ：2021/10/2 17:16
 * HISTORY :
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthUserDao authUserDao;

    @Override
    public Long handle(AuthResponse login) {
        AuthUser authUser = (AuthUser) login.getData();
        MyAuthUser myAuthUser = new MyAuthUser();
        BeanUtils.copyProperties(authUser, myAuthUser);
        myAuthUser.setGender(authUser.getGender().getCode());
        return ifExit(myAuthUser);
    }

    /**
     * 判断是否存在
     *
     * @param myAuthUser
     * @return
     */
    public Long ifExit(MyAuthUser myAuthUser) {
        QueryWrapper<MyAuthUser> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("tenant_id", myAuthUser.getTenantId());
        queryWrapper.eq("uuid", myAuthUser.getUuid());
        queryWrapper.eq("source", myAuthUser.getSource());
        MyAuthUser myAuthUserExit = authUserDao.selectOne(queryWrapper);
        if (myAuthUserExit == null) {
            //保存信息
            authUserDao.insert(myAuthUser);
            //让其通过手机号或邮箱绑定平台账号
            return null;
        } else {
            //更新信息
            authUserDao.update(myAuthUser, queryWrapper);
            //获取平台用户ID
            Long userId = myAuthUserExit.getUserId();
            return userId;
        }
    }
}
